package com.helloblog.web.action;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.hello.service.impl.CoreSerivceImpl;
import com.helloblog.domain.Article;
import com.helloblog.domain.User;
import com.helloblog.utils.WebUtils;

public class ArticleAction extends DispatchAction {
	/*
	 * 未指定参数默认执行的方法
	 */
	@Override
	protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			CoreSerivceImpl service = new CoreSerivceImpl();
			List<Article> list = service.listAllArticle();
			request.setAttribute("list", list);
			return mapping.findForward("blog_index");
		} catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward("failed");
		}
		
	}
	
	
	//发布文章
	public ActionForward release(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		try {
			Article a = (Article) form;
			CoreSerivceImpl service = new CoreSerivceImpl();
			if(request.getSession().getAttribute("user")!=null){
				User user = (User) request.getSession(false).getAttribute("user");
				a.setRelease_datetime(new Date());
				a.setUser_id(user.getId());
				a.setBlog_id(user.getId());
				service.releaseArticle(a);
				return mapping.findForward("release_sucess");
			}
			return mapping.findForward("failed");
		} catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward("failed");
		}
		
	}
	
	//列出文章
		public ActionForward listAll(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response){
			try {
				CoreSerivceImpl service = new CoreSerivceImpl();
				List<Article> list = service.listAllArticle();
				request.setAttribute("list", list);
				return mapping.findForward("blog_index");
			} catch (Exception e) {
				e.printStackTrace();
				return mapping.findForward("failed");
			}
			
		}
		
	//查看文章
		public ActionForward show(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response){
			try {
				String id = request.getParameter("id");
				CoreSerivceImpl service = new CoreSerivceImpl();
				Article a = service.getArticle(id);
				request.setAttribute("a", a);
				return mapping.findForward("blog_show");
			} catch (Exception e) {
				e.printStackTrace();
				return mapping.findForward("failed");
			}
			
		}
	
}
